package leetcode.array.remove;

import java.util.Arrays;

/**
 * 27. 移除元素
 *
 * 删除指定的值的元素
 *
 */
public class RemoveElement {

    public static void main(String[] args) {
        RemoveElement solution = new RemoveElement();

        int[] nums = {0, 1, 2, 2, 3, 0, 4, 2};
        int len = solution.removeElement(nums, 2);
        System.out.println(len);
        System.out.println(Arrays.toString(nums));
    }

    /**
     * 双指针 写法复杂
     *
     * @param nums 数组
     * @param val  指定值
     * @return
     */
    public int removeElement0(int[] nums, int val) {
        int fast = 0;
        int slow = 0;
        while (fast < nums.length && slow < nums.length) {
            if (nums[slow] != val) {
                slow++;
            } else {
                fast = slow + 1;
                while (fast < nums.length && nums[fast] == val) {
                    fast++;
                }
                if (fast < nums.length) {
                    // 交换位置
                    int temp = nums[slow];
                    nums[slow] = nums[fast];
                    nums[fast] = temp;
                    slow++;
                    fast++;
                }
            }
        }
        return slow;
    }

    /**
     * 双指针 官方写法
     *
     * @param nums
     * @param val
     * @return
     */
    public int removeElement(int[] nums, int val) {
        int left = 0;
        int right = nums.length;
        while (left < right) {
            if (nums[left] == val) {
                nums[left] = nums[right - 1];
                right--;
            } else {
                left++;
            }
        }
        return left;
    }

}
